package com.acme.bankapp;

import java.io.IOException;

import com.acme.bankapp.exception.DeserializationException;
import com.acme.bankapp.server.BankServer;
import com.acme.bankapp.service.bank.BankService;

public class BankApplication {

    protected static final String CLI_PARAM_LOAD_FROM_FILE = "-loadfeed";
    protected static final String CLI_PARAM_LOAD_FROM_FILE_ALT = "-loadbank";
    protected static final String CLI_PARAM_START_SERVER = "-server";
    protected static final int NOT_FIND = -1;

    public static int findFirst(final String value, final String[] array) {
	if (array.length == 0) {
	    return NOT_FIND;
	}
	for (int i = 0; i < array.length; i++) {
	    if (array[i].equals(value)) {
		return i;
	    }
	}
	return NOT_FIND;
    }

    public static void main(final String[] args) {
	BankService bankService = null;
	int loadFromFileParamID = Math.max(
		findFirst(CLI_PARAM_LOAD_FROM_FILE, args),
		findFirst(CLI_PARAM_LOAD_FROM_FILE_ALT, args));
	int startServerParamID = findFirst(CLI_PARAM_START_SERVER, args);

	if (loadFromFileParamID != NOT_FIND
		&& paramValueExists(loadFromFileParamID, args)) {
	    String fileName = args[loadFromFileParamID + 1];
	    bankService = initFromFile(fileName, bankService);
	}
	if (bankService == null) {
	    return;
	}
	bankService.printBalance();
	bankService.printMaximumAmountToWithdraw();
	if (startServerParamID != NOT_FIND) {
	    startServer(bankService);
	}
    }

    public static boolean paramValueExists(final int paramID,
	    final String args[]) {
	return args.length > paramID + 1;
    }

    private static void startServer(final BankService bankService) {
	BankServer.startServer(bankService);
    }

    protected static BankService initFromFile(final String fileName,
	    BankService bankService) {
	try {
	    bankService = BankService.loadBank(fileName);
	} catch (DeserializationException e) {
	    System.err.println("Error on reading file " + fileName
		    + ". Bad format.");
	    System.out.println(e.getMessage());
	    e.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	}
	return bankService;
    }

}
